<?php

namespace app\api\controller;

use app\common\controller\Api;
use Exception;
use \think\exception\PDOException;
use think\Db;

require_once "../extend/WxPay/WxPay.Api.php";
require_once '../extend/WxPay/WxPay.Notify.php';
require_once "../extend/WxPay/WxPay.Config.php";
require_once '../extend/WxPay/Log.php';

//初始化日志
$logHandler = new \CLogFileHandler("D:\\wwwroot\\YiDao\\extend\\" . date('Y-m-d') . '.log');
$log = \Log::Init($logHandler, 15);

class Health extends Api
{
	protected $noNeedLogin = '*';

	private static 		$APPID = "wx956ae520bc5acf4d";
	private static		$SECRET = "8487b0bfb3cc81b0c08e3de25a0846db";

	// openid验证
	private function checkOpenid($openid, $auth = null)
	{
		try {
			// 查询用户表
			$sql = "select *, (SELECT  TIMESTAMPDIFF(YEAR,(select birthday from hd_member where openid='$openid'), CURDATE()) )AS age from hd_member where openid='$openid'";
			$result = Db::query($sql);
			//有用户，返回用户信息
			if (count($result) != 0) {
				$ret['code'] = 200;
				$ret['message'] = 'Success';
				$ret['data'] = $result;
			} else {
				//没有用户，返回错误信息
				$ret['code'] = 301;
				$ret['message'] = '用户不存在or没有用户openid';
			}

			return $ret;
		} catch (PDOException $e) {
			$ret['code'] = 201;
			$ret['message'] = '请求失败';
			return $ret;
		}
	}

	//获取OPENID
	public function getOpenid()
	{
		$params = $this->request->param();
		$recOpenid = isset($params["recOpenid"]) ? $params["recOpenid"] : "";
		$code = $params["code"];
		$orderNum = isset($params["orderNum"]) ? $params["orderNum"] : "";

		Db::startTrans();
		try {
			$get_token_url =  'https://api.weixin.qq.com/sns/jscode2session?appid=' . self::$APPID . '&secret=' . self::$SECRET . '&js_code=' . $code . '&grant_type=authorization_code';
			$curl = curl_init();
			curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
			curl_setopt($curl, CURLOPT_TIMEOUT, 500);
			curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
			curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
			curl_setopt($curl, CURLOPT_URL, $get_token_url);

			$res = curl_exec($curl);
			curl_close($curl);
			$json_obj = json_decode($res, true);
			$openid = $json_obj["openid"];
			$session_key = $json_obj["session_key"];

			$sql = "select * from hd_member where openid='{$openid}'";
			$result = Db::query($sql);
			if (count($result) == 0) {
				$sql = "select max_member_no from hd_member_no where id ='1'";
				$res = Db::query($sql);
				$memberNo = json_encode($res[0]["max_member_no"]) + 1;
				
				$sql = "insert into hd_member (m_no,openid,recommender_id, session_key) values ('{$memberNo}','{$openid}','{$recOpenid}','{$session_key}')";
				Db::execute($sql);
				$sql = "update hd_member_no set max_member_no='{$memberNo}' where id ='1'";
				Db::execute($sql);
			} else {
				$sql = "update hd_member set session_key='{$session_key}' where openid='{$openid}'";
				$res = Db::execute($sql);
			}

			// 若用户是扫码下单->注册 的，此时要去订单表里 插入用户的openid
			if ($orderNum) {
				$sql = "update hd_order set openid='$openid' where number='$orderNum'";
				Db::execute($sql);
			}

			$ret['code'] = 200;
			$ret['message'] = 'Success';
			$ret['openid'] = $openid;
			$ret['session_key'] = $session_key;
			Db::commit();
			return json($ret);
		} catch (PDOException $e) {
			Db::rollback();
			$ret['code'] = 201;
			$ret['message'] = 'Fail' . $e;
			return json($ret);
		}
	}

	//-------------------------------------------------------会员（用户）-----------------------------------------------------
	//更新用户昵称、头像
	public function updateUserInfo()
	{
		$params = $this->request->param();
		$openid = $params["openid"];
		$memberRes = $this->checkOpenid($openid);

		if ($memberRes["code"] != 200) {
			$ret['code'] = 201;
			$ret['message'] = '无权限操作';
			return json($ret);
		}

		$nickName = $params["nickName"];
		$headUrl = $params["headUrl"];
		$openid = $params["openid"];
		$recOpenid = isset($params["recOpenid"]) ? $params["recOpenid"] : "";

		try {
			$sql = "
			update hd_member set  nick_name='$nickName',avator_url='$headUrl', recommender_id = (case
			when ISNULL(recommender_id) then '$recOpenid'
			else recommender_id
			end)
			where openid='$openid'
			";
			Db::execute($sql);

			$ret['code'] = 200;
			$ret['message'] = 'Success';

			return json($ret);
		} catch (PDOException $e) {
			$ret['code'] = 201;
			$ret['message'] = 'Fail' . $e;
			return json($ret);
		}
	}

	public function updateUser()
	{
		$params = $this->request->param();
		$openid = $params["openid"];
		$memberRes = $this->checkOpenid($openid);

		if ($memberRes["code"] != 200) {
			$ret['code'] = 201;
			$ret['message'] = '无权限操作';
			return json($ret);
		}

		$realName = $params["realName"];
		$birthday = $params["birthday"];
		$mobile = $params["mobile"];
		$gender = $params["gender"];

		try {
			$sql = "update hd_member set real_name='$realName',birthday='$birthday', mobile='$mobile', gender='$gender' where openid='$openid'";
			Db::execute($sql);

			$ret['code'] = 200;
			$ret['message'] = 'Success';

			return json($ret);
		} catch (PDOException $e) {
			$ret['code'] = 201;
			$ret['message'] = 'Fail' . $e;
			return json($ret);
		}
	}

	//获取用户信息
	public function getUserInfo()
	{
		$data = $this->request->param();
		$openid = $data["openid"];
		$memberRes = $this->checkOpenid($openid);

		if ($memberRes["code"] != 200) {
			$ret['code'] = 201;
			$ret['message'] = '无权限操作';
			return json($ret);
		}

		$memberNum = $memberRes["data"][0]["m_no"];
		try {
			// 获得用户钱包信息
			$sql = "select IFNULL(sum(current_fee),0) as totalMoney,
				IFNULL(sum(case when  to_days(createtime) = to_days(now()) then current_fee else 0 end),0) as dayMoney
				from hd_member_bill
				where current_fee > 0 and member_no = '$memberNum'";
			$ret["data"]["billData"] = Db::query($sql);

			// 用户是 医生 也是企业负责人
			if ($memberRes["data"][0]["doctor_id"] && $memberRes["data"][0]["merchant_id"]) {
				$merchantId = $memberRes["data"][0]["merchant_id"];
				$doctorId = $memberRes["data"][0]["doctor_id"];

				// 获得 企业地址
				$sql = "select *  from hd_merchant where merchant_id='$merchantId'";
				$merchantRes = Db::query($sql);
				$ret["data"]["merchant"] = $merchantRes;
				$ret["data"]['isMerchant'] = 1;
				$ret["data"]['isDoctor'] = 1;
			} elseif ($memberRes["data"][0]["doctor_id"]) { // 用户是 医生
				$doctorId = $memberRes["data"][0]["doctor_id"];
				// 获得 医生诊所地址
				$sql = "select hd_merchant.* 
					from hd_merchant
					left join hd_admin on hd_merchant.merchant_id = hd_admin.merchant_id
					where hd_admin.id='$doctorId'";
				$merchantRes = Db::query($sql);
				$ret["data"]["merchant"] = $merchantRes;
				$ret["data"]['isDoctor'] = 1;
				$ret["data"]['isMerchant'] = 0;
			} elseif ($memberRes["data"][0]["merchant_id"]) { // 用户是 企业负责人
				$merchantId = $memberRes["data"][0]["merchant_id"];
				// 获得 企业地址
				$sql = "select *  from hd_merchant where merchant_id='$merchantId'";
				$merchantRes = Db::query($sql);
				$ret["data"]["merchant"] = $merchantRes;
				$ret["data"]['isMerchant'] = 1;
				$ret["data"]['isDoctor'] = 0;
			}

			// 小程序审核开关
			$sql = "select paramvalue from hd_param where param = '小程序审核开关'";
			$paramRes = Db::query($sql);
			$verifyOn = count($paramRes) != 0 ? $paramRes[0]["paramvalue"] : "";

			// 用户最近使用的银行卡
			$sql = "select bank,account_name,bank_account from hd_withdraw where member_no='$memberNum' order by id desc";
			$bankRes = Db::query($sql);
			$bankInfo = count($bankRes) != 0 ? $bankRes[0] : "";

			// 用户提现费率
			$sql = "select paramvalue from hd_param where param = '提现手续费'";
			$res = Db::query($sql);
			$serviceCharge = $res[0]["paramvalue"];

			$ret["data"]["bank"] = $bankInfo;
			$ret["data"]["serviceCharge"] = $serviceCharge;
			$ret["data"]["member"] = $memberRes["data"];
			$ret['verifyOn'] = $verifyOn;
			$ret['code'] = 200;
			$ret['message'] = 'Success';

			return json($ret);
		} catch (PDOException $e) {
			$ret['code'] = 201;
			$ret['message'] = 'Fail' . $e;
			return json($ret);
		}
	}

	//编辑会员地址(增加、更新、删除)
	public function editAddress()
	{
		$params = $this->request->param();
		$openid = $params["openid"];
		$res = $this->checkOpenid($openid);

		$act = isset($params["act"]) ? $params["act"] : "";
		$id = isset($params["id"]) ? $params["id"] : "";
		$userName = isset($params["userName"]) ? $params["userName"] : "";
		$userMobile = isset($params["userMobile"]) ? $params["userMobile"] : "";
		$city = isset($params["city"]) ? $params["city"] : "";
		$address = isset($params["address"]) ? $params["address"] : "";
		$detailAddress = isset($params["detailAddress"]) ? $params["detailAddress"] : "";
		$isDefault = isset($params["isDefault"]) ? $params["isDefault"] : "";
		$isDefault = $isDefault == "false" ? 0 : 1;

		Db::startTrans();
		try {
			if ($act == "add") {
				if ($isDefault == "1") {  // 1代表默认，0代表非默认
					//取消之前的默认地址
					$sql = "update hd_address set isdefault='0' where openid='{$openid}'";
					Db::execute($sql);
				}
				$sql = "insert into hd_address (user_name,openid,user_mobile,city,address,detail_address,isdefault) 
				values ('{$userName}','{$openid}','{$userMobile}','{$city}','{$address}','{$detailAddress}','{$isDefault}')";
			} elseif ($act == "edit") {
				if ($isDefault == "1") {  // 1代表默认，0代表非默认
					//取消之前的默认地址
					$sql = "update hd_address set isdefault='0' where openid='{$openid}'";
					Db::execute($sql);
				}
				$sql = "update hd_address set user_name='{$userName}',openid='{$openid}',user_mobile='{$userMobile}',city='{$city}',
				address='{$address}',detail_address='{$detailAddress}',isdefault='{$isDefault}' where id={$id}";
			} elseif ($act == "delete") {
				$sql = "delete from hd_address where openid='{$openid}' and id={$id}";
			} else {
				$ret['code'] = 201;
				$ret['message'] = '请求操作不存在';
				Db::commit();
				return json($ret);
			}

			$result = Db::execute($sql);
			if ($result) { // 有执行记录
				$ret['code'] = 200;
				$ret['message'] = 'Success';
			} else {   //  无执行记录
				$ret['code'] = 200;
				$ret['message'] = '无影响记录';
			}

			Db::commit();
			return json($ret);
		} catch (PDOException $e) {
			Db::rollback();
			$ret['code'] = 201 . $e;
			$ret['message'] = '保存失败，请检查网络原因';
			return json($ret);
		}
	}

	public function getUserDefaultAddress()
	{
		$params = $this->request->param();
		$openid = isset($params["openid"]) ? $params["openid"] : "";

		$res = $this->checkOpenid($openid);

		if ($res["code"] != 200) {
			$ret['code'] = 201;
			$ret['message'] = '无权限操作';
			return json($ret);
		}

		try {
			// 获得会员的默认收货地址
			$sql = "select * from hd_address where openid='{$openid}' and isdefault='1' ";
			$result = Db::query($sql);
			$address = $result[0];

			$ret["code"] = 200;
			$ret["message"] = "Success";
			$ret["address"] = $address;

			return json($ret);
		} catch (PDOException $e) {
			$ret['code'] = 201;
			$ret['message'] = 'Fail' . $e;
			return json($ret);
		}
	}

	//获取会员地址列表
	public function getUserAddressList()
	{
		$params = $this->request->param();
		$openid = $params["openid"];
		$this->checkOpenid($openid);

		Db::startTrans();
		try {
			$sql = "select * from hd_address where openid='${openid}'";
			$result = Db::query($sql);

			if (count($result) != 0) {
				$ret['code'] = 200;
				$ret['message'] = 'Success';
				$ret['data'] = $result;
			} else {
				$ret['code'] = 202;
				$ret['message'] = '尚未添加地址';
			}

			Db::commit();
			return json($ret);
		} catch (PDOException $e) {
			Db::rollback();
			$ret['code'] = 201;
			$ret['message'] = '查询地址列表失败，请检查网络';
			return json($ret);
		}
	}

	// 提现
	public function withDraw()
	{
		$params = $this->request->param();
		$openId = isset($params["openid"]) ? $params["openid"] : "";

		$memberRes = $this->checkOpenid($openId);
		if ($memberRes["code"] != 200) {
			$ret['code'] = 201;
			$ret['message'] = '无权限操作';
			return json($ret);
		}

		try {
			$memberNum = $memberRes["data"][0]["m_no"];
			$businessNo = build_order_num();	// 提现流水号

			$bankAccount = isset($params["bankAccount"]) ? $params["bankAccount"] : "";
			$bankName = isset($params["bankName"]) ? $params["bankName"] : "";
			$userName = isset($params["userName"]) ? $params["userName"] : "";
			$type = isset($params["type"]) ? $params["type"] : "";
			$userType = $type == "member" ? "用户" : "企业";
			$outMoney = isset($params["outMoney"]) ? $params["outMoney"] : "";

			Db::startTrans();
			$sql = "select paramvalue from hd_param where param = '提现手续费'";
			$res = Db::query($sql);
			$serviceCharge = $res[0]["paramvalue"];
			$receiveMoney = $outMoney * (1 - $serviceCharge);

			if ($type == "member") {   //用户提现
				// --插入提现表
				$sql = "INSERT INTO hd_withdraw(`member_no`, `business_no`,`status`,`user_type`, `money`, `service_charge`,  `receive_money`, `bank`, `account_name`, `bank_account`) 
										VALUES ('$memberNum','$businessNo', '待审核','$userType', $outMoney, $serviceCharge, $receiveMoney, '$bankName', '$userName', '$bankAccount');
				";
				Db::execute($sql);

				// --更新用户余额
				$balance = $memberRes["data"][0]["balance"] - $outMoney;
				$sql = "update hd_member set balance='$balance' where m_no='$memberNum'";
				Db::execute($sql);

				// --插入账单表
				$sql = "INSERT INTO `hd_member_bill`(`member_no`, `bill_item`, `business_no`, `user_type`, `mb_type`, `mb_balance`, `current_fee`) 
												VALUES ($memberNum, '用户提现', '$businessNo', 	'用户', 	'现金', 	$balance, 	-$outMoney);
				";
				Db::execute($sql);
			} else {	//  企业提现 merchant
				$merchantId = $memberRes["data"][0]["merchant_id"]; // 用户对应的企业ID
				// --插入提现表
				$sql = "INSERT INTO hd_withdraw(`member_no`, `merchant_id`,`business_no`,`status`,`user_type`, `money`, `service_charge`,  `receive_money`, `bank`, `account_name`, `bank_account`) 
										VALUES ('$memberNum','$merchantId','$businessNo', '待审核','$userType', $outMoney, $serviceCharge, $receiveMoney, '$bankName', '$userName', '$bankAccount');
				";
				Db::execute($sql);

				// --更新企业余额
				$sql = "select * from hd_merchant where merchant_id='$merchantId'";
				$merchantRes = Db::query($sql);
				$balance = $merchantRes[0]["merchant_balance"] - $outMoney;
				$sql = "update hd_merchant set merchant_balance='$balance' where merchant_id='$merchantId'";
				Db::execute($sql);

				// --插入账单表
				$sql = "INSERT INTO `hd_member_bill`(`member_no`, `bill_item`, `business_no`, `user_type`, `mb_type`, `mb_balance`, `current_fee`) 
											VALUES ($merchantId, '企业提现', '$businessNo', 	'企业', 	'现金', 	$balance,       -$outMoney);
				";
				Db::execute($sql);
			}

			Db::commit();
			$ret['code'] = 200;
			$ret['message'] = 'Success';
			return json($ret);
		} catch (PDOException $e) {
			Db::rollback();
			$ret['code'] = 201;
			$ret['message'] = 'Fail' . $e;
			return json($ret);
		}
	}

	// 增加银行卡
	public function addBankcard()
	{
		$params = $this->request->param();
		$openId = isset($params["openid"]) ? $params["openid"] : "";

		$memberRes = $this->checkOpenid($openId);
		if ($memberRes["code"] != 200) {
			$ret['code'] = 201;
			$ret['message'] = '无权限操作';
			return json($ret);
		}

		try {
			$memberNum = $memberRes[0]["m_no"];
			$bankAccount = isset($params["bankAccount"]) ? $params["bankAccount"] : "";
			$bankName = isset($params["bankName"]) ? $params["bankName"] : "";
			$userName = isset($params["userName"]) ? $params["userName"] : "";

			$sql = "insert into hd_bank(member_no,bank_account,bank_name,user_name) 
								values('$memberNum','$bankAccount','$bankName','$userName')";
			Db::execute($sql);

			$ret['code'] = 200;
			$ret['message'] = 'Success';
			return json($ret);
		} catch (PDOException $e) {
			$ret['code'] = 201;
			$ret['message'] = 'Fail' . $e;
			return json($ret);
		}
	}

	// 获得银行卡列表
	public function getBankcardList()
	{
		$params = $this->request->param();
		$openId = isset($params["openid"]) ? $params["openid"] : "";

		$memberRes = $this->checkOpenid($openId);
		if ($memberRes["code"] != 200) {
			$ret['code'] = 201;
			$ret['message'] = '无权限操作';
			return json($ret);
		}

		try {
			$memberNum = $memberRes[0]["m_no"];
			$sql = "select * from hd_bank where member_no='$memberNum'";
			$bankRes = Db::query($sql);
			if (count($bankRes) != 0) {
				$ret['code'] = 200;
				$ret['message'] = 'Success';
				$ret["cardList"] = $bankRes;

				return json($ret);
			} else {
				$ret['code'] = 200;
				$ret['message'] = '暂无银行卡';

				return json($ret);
			}
		} catch (PDOException $e) {
			$ret['code'] = 201;
			$ret['message'] = 'Fail' . $e;

			return json($ret);
		}
	}

	//------------------------------------------------------------------检测 产品--------------------------------------------------------
	// 获得检测企业（检测中心，体检企业）
	public function getDetectOrganization()
	{
		$prefix = "https://" . $_SERVER['SERVER_NAME'] . ":" . $_SERVER["SERVER_PORT"];

		try {
			$sql = "SELECT merchant_id, merchant_name,pay_rider,createtime,comments,address,merchant_tel,
				REPLACE(merchant_image,'/uploads','$prefix/uploads') as merchant_image 
				FROM hd_merchant
				WHERE merchant_type IN ('检测中心', '体检企业');";
			$merchantRes = Db::query($sql);
			if (count($merchantRes) != 0) {
				$ret["code"] = 200;
				$ret["message"] = "Success";
				$ret["data"] = $merchantRes;
			} else {
				$ret["code"] = 200;
				$ret["message"] = "暂无企业";
			}

			return json($ret);
		} catch (PDOException $e) {
			$ret["code"] = 201;
			$ret["message"] = "Fail";
			return json($ret);
		}
	}
	// 获得某个检测企业（检测中心，体检企业）的产品
	public function getDetectProductByMId()
	{
		$params = $this->request->param();
		$mid = $params["mid"];
		$prefix = "https://" . $_SERVER['SERVER_NAME'] . ":" . $_SERVER["SERVER_PORT"];

		try {
			$sql = "SELECT
				hd_product.id,hd_product.category_id,hd_product.specs_id,hd_product.manufactor_id,hd_product.role_id,hd_product.merchant_id,
				hd_product.product_name,hd_product.brand,hd_product.unit,hd_product.amount,
				REPLACE(hd_product.small_image,'/uploads','{$prefix}/uploads') as small_image ,
				REPLACE(hd_product.product_images,'/uploads','{$prefix}/uploads') as product_images ,
				hd_product.market_price,hd_product.sale_price,
				hd_product.status,hd_product.is_hot,hd_product.brief_introduction,
				REPLACE(hd_product.detail_introduction," .  "'<img src=\"'," . "'<img src=\"" . $prefix . "') as descript,
				hd_product.clinic_share,hd_product.SGS_share,hd_product.recommender_share,
				hd_product.create_time,hd_product.comments,
				hd_merchant.merchant_name,hd_manufactor.manu_name,hd_category.name AS category_name
				FROM
				hd_product
				LEFT JOIN hd_merchant ON hd_product.merchant_id = hd_merchant.merchant_id
				LEFT JOIN hd_manufactor ON hd_product.manufactor_id = hd_manufactor.manu_id
				LEFT JOIN hd_category ON hd_product.category_id = hd_category.id
				WHERE
				hd_merchant.merchant_id = '{$mid}'";
			$result = Db::query($sql);
			if (count($result) != 0) {
				$ret["code"] = 200;
				$ret["message"] = "Success";
				$ret["data"] = $result;
			} else {
				$ret["code"] = 200;
				$ret["message"] = "暂无产品";
			}

			return json($result);
		} catch (PDOException $e) {
			$ret["code"] = 201;
			$ret["message"] = "Fail";
			return json($result);
		}
	}
	// 获得某个检测企业（体检套餐）的产品
	public function getPackageProductByMId()
	{
		$params = $this->request->param();
		$mid = $params["mid"];
		$prefix = "https://" . $_SERVER['SERVER_NAME'] . ":" . $_SERVER["SERVER_PORT"];

		try {
			$sql = "SELECT
		hd_product.id,hd_product.category_id,hd_product.specs_id,hd_product.manufactor_id,hd_product.role_id,hd_product.merchant_id,
		hd_product.product_name,hd_product.brand,hd_product.unit,hd_product.amount,
		REPLACE(hd_product.small_image,'/uploads','{$prefix}/uploads') as small_image ,
		REPLACE(hd_product.product_images,'/uploads','{$prefix}/uploads') as product_images ,
		hd_product.market_price,hd_product.sale_price,
		hd_product.status,hd_product.is_hot,hd_product.brief_introduction,
		REPLACE(hd_product.detail_introduction," .  "'<img src=\"'," . "'<img src=\"" . $prefix . "') as descript,
		hd_product.clinic_share,hd_product.SGS_share,hd_product.recommender_share,
		hd_product.create_time,hd_product.comments,
		hd_merchant.merchant_name,hd_manufactor.manu_name,hd_category.name AS category_name
		FROM
		hd_product
		LEFT JOIN hd_merchant ON hd_product.merchant_id = hd_merchant.merchant_id
		LEFT JOIN hd_manufactor ON hd_product.manufactor_id = hd_manufactor.manu_id
		LEFT JOIN hd_category ON hd_product.category_id = hd_category.id
		WHERE
		hd_merchant.merchant_id = '{$mid}' and hd_category.type ='package'";
			$result = Db::query($sql);
			if (count($result) != 0) {
				$ret["code"] = 200;
				$ret["message"] = "Success";
				$ret["data"] = $result;
			} else {
				$ret["code"] = 200;
				$ret["message"] = "暂无产品";
			}

			return json($result);
		} catch (PDOException $e) {
			$ret["code"] = 201;
			$ret["message"] = "Fail";
			return json($result);
		}
	}
	// 获得诊所
	public function getClinics()
	{
		$prefix = "https://" . $_SERVER['SERVER_NAME'] . ":" . $_SERVER["SERVER_PORT"];

		try {
			$sql = "SELECT merchant_id, merchant_name,pay_rider,createtime,comments,address,merchant_tel,
				REPLACE(merchant_image,'/uploads','$prefix/uploads') as merchant_image 
				FROM hd_merchant
				WHERE merchant_type ='诊所';";
			$merchantRes = Db::query($sql);
			if (count($merchantRes) != 0) {
				$ret["code"] = 200;
				$ret["message"] = "Success";
				$ret["data"] = $merchantRes;
			} else {
				$ret["code"] = 200;
				$ret["message"] = "暂无诊所";
			}

			return json($ret);
		} catch (PDOException $e) {
			$ret["code"] = 201;
			$ret["message"] = "Fail" . $e;
			return json($ret);
		}
	}

	//获得 检测企业的产品(二维数组)
	public function getDetectProduct()
	{
		$prefix = "https://" . $_SERVER['SERVER_NAME'] . ":" . $_SERVER["SERVER_PORT"];

		try {
			$sql = "select merchant_id ,merchant_name from hd_merchant WHERE merchant_type IN ('检测中心', '体检企业');";
			$merchantRes = Db::query($sql);
			for ($i = 0; $i < count($merchantRes); $i++) {
				$merchantId = $merchantRes[$i]["merchant_id"];
				$merchantName = $merchantRes[$i]["merchant_name"];
				$sql = "SELECT
					hd_product.id,hd_product.category_id,hd_product.specs_id,hd_product.manufactor_id,hd_product.role_id,hd_product.merchant_id,
					hd_product.product_name,hd_product.brand,hd_product.unit,hd_product.amount,
					REPLACE(hd_product.small_image,'/uploads','{$prefix}/uploads') as small_image ,
					REPLACE(hd_product.product_images,'/uploads','{$prefix}/uploads') as product_images ,
					hd_product.market_price,hd_product.sale_price,
					hd_product.status,hd_product.is_hot,hd_product.brief_introduction,hd_product.detail_introduction,
					hd_product.clinic_share,hd_product.SGS_share,hd_product.recommender_share,
					hd_product.create_time,hd_product.comments,
					hd_manufactor.manu_name,hd_category.name AS category_name
					FROM hd_product
					LEFT JOIN hd_manufactor ON hd_product.manufactor_id = hd_manufactor.manu_id
					LEFT JOIN hd_category ON hd_product.category_id = hd_category.id
					WHERE hd_product.merchant_id={$merchantId}";
				$productRes = Db::query($sql);

				$res[$i]["merchantID"] = $merchantId;
				$res[$i]["merchantName"] = $merchantName;
				$res[$i]["productData"] = $productRes;
				$res[$i]["merchantTotal"] = "0";
			}

			$ret["code"] = 200;
			$ret["message"] = "Success";
			$ret["data"] = $res;

			return json($ret);
		} catch (PDOException $e) {
			$ret["code"] = 201;
			$ret["message"] = "Fail";
			return json($ret);
		}
	}

	//------------------------------------------------------------------检测中心分类--------------------------------------------------------

	//获取检测产品分类信息 -- 用于左侧导航栏（点击检测企业后进入分类页面）
	public function getDetectCategoryByMid()
	{
		$params = $this->request->param();
		$mid = isset($params["mid"]) ? $params["mid"] : "";
		try {
			// 取得type为detect_category的所有顶层分类
			$sql = "select name,id,type from  hd_category where type ='detect_category' and pid='0'";
			$cateResult = Db::query($sql);
			if (count($cateResult) != 0) {
				for ($i=0; $i < count($cateResult); $i++) { 
					$cateId = $cateResult[$i]["id"];
					$cateName = $cateResult[$i]["name"];
					$sql = "select * from  hd_product where category_id=$cateId and merchant_id = '$mid'";
					$productRes = Db::query($sql);

					$ret['data'][$i]['cname'] = $cateName;
					$ret['data'][$i]['cid'] = $cateId;
					$ret['data'][$i]['productData'] = $productRes;
				}

				$ret['code'] = 200;
				$ret['message'] = 'Success';
			} else {
				$ret['code'] = 200;
				$ret['message'] = '暂无检测项目';
			}

			// // 取得type为detect_category 且 name=“检测中心”的分类ID
			// $sql = "select id from  hd_category where pid='0' and name='检测中心'";
			// $jcIdRes = Db::query($sql);
			// $jcId = count($jcIdRes) != 0 ? $jcIdRes[0]["id"] : 0;
			// // 默认显示 左侧第一个导航Item即检测中心 的数据
			// $sql = "select * from  hd_product where category_id=$jcId and merchant_id = '$mid'";
			// $jcProducts = Db::query($sql);
			// $ret["products"] = $jcProducts;

			return json($ret);
		} catch (PDOException $e) {
			$ret['code'] = 201;
			$ret['message'] = 'Fail' . $e;
			return json($ret);
		}
	}

	//获取检测产品信息 -- 分类产品信息（通过检测企业和分类Id筛选）
	public function getDetectProductById()
	{
		$prefix = "https://" . $_SERVER['SERVER_NAME'] . ":" . $_SERVER["SERVER_PORT"];

		$params = $this->request->param();
		$id = isset($params["id"]) ? $params["id"] : "";
		$mid = isset($params["mid"]) ? $params["mid"] : "";

		try {
			$sql = "
				SELECT id, category_id, specs_id, manufactor_id, role_id, merchant_id,
					product_name, brand, unit, amount,
					REPLACE(hd_product.small_image,'/uploads','{$prefix}/uploads') as small_image ,
					REPLACE(hd_product.product_images,'/uploads','{$prefix}/uploads') as product_images ,
					market_price, sale_price, status, is_hot, brief_introduction, detail_introduction,
					clinic_share, SGS_share, recommender_share, create_time, comments
				FROM
					hd_product
				where category_id = '$id' and merchant_id = '$mid';
				";
			$result = Db::query($sql);
			if (count($result) != 0) {
				$ret['code'] = 200;
				$ret['message'] = 'Success';
				$ret['data'] = $result;
			} else {
				$ret['code'] = 201;
				$ret['message'] = '暂无产品信息';
			}

			return json($ret);
		} catch (PDOException $e) {
			$ret['code'] = 201;
			$ret['message'] = 'Fail' . $e;
			return json($ret);
		}
	}

	public function getSearchList()
	{
		$prefix = "https://" . $_SERVER['SERVER_NAME'] . ":" . $_SERVER["SERVER_PORT"];

		$params = $this->request->param();
		$searchWords = isset($params["searchWords"]) ? $params["searchWords"] : "";
		$mid = isset($params["mid"]) ? $params["mid"] : "";

		try {
			$sql = "
				SELECT id, category_id, specs_id, manufactor_id, role_id, merchant_id,
					product_name, brand, unit, amount,
					REPLACE(hd_product.small_image,'/uploads','{$prefix}/uploads') as small_image ,
					REPLACE(hd_product.product_images,'/uploads','{$prefix}/uploads') as product_images ,
					market_price, sale_price, status, is_hot, brief_introduction, detail_introduction,
					clinic_share, SGS_share, recommender_share, create_time, comments
				FROM
					hd_product
				where merchant_id = '$mid' and product_name like '%$searchWords%';
				";
			$result = Db::query($sql);
			if (count($result) != 0) {
				$ret['code'] = 200;
				$ret['message'] = 'Success';
				$ret['data'] = $result;
			} else {
				$ret['code'] = 201;
				$ret['message'] = '暂无产品信息';
			}

			return json($ret);
		} catch (PDOException $e) {
			$ret['code'] = 201;
			$ret['message'] = 'Fail' . $e;
			return json($ret);
		}
	}

	//------------------------------------------------------------------商城 产品--------------------------------------------------------
	//获取商品 分类信息 -- 用于左侧导航栏
	public function getShopCategory()
	{
		Db::startTrans();
		try {
			$sql = "select name,id from  hd_category where type='product' and pid='0'";
			$result = Db::query($sql);
			if (count($result) != 0) {
				$ret['code'] = 200;
				$ret['message'] = 'Success';
				$ret['data'] = $result;
			} else {
				$ret['code'] = 200;
				$ret['message'] = '暂无商品类别信息';
			}

			Db::commit();
			return json($ret);
		} catch (PDOException $e) {
			Db::rollback();
			$ret['code'] = 201;
			$ret['message'] = 'Fail' . $e;
			return json($ret);
		}
	}

	//获取某类别 产品    --- 左侧导航栏点击某个类别，返回属于该类别的商品
	public function getCategoryById()
	{
		$prefix = "https://" . $_SERVER['SERVER_NAME'] . ":" . $_SERVER["SERVER_PORT"];

		$params = $this->request->param();
		$id = isset($params["id"]) ? $params["id"] : "";

		try {
			$sql = "
				select id,pid,type,name,status,createtime,updatetime,comments,
				REPLACE(hd_category.image,'/uploads','{$prefix}/uploads') as image 
				from hd_category
				where FIND_IN_SET(hd_category.id,getTreeChlid({$id}));
			";
			$result = Db::query($sql);
			if (count($result) != 0) {
				$ret['code'] = 200;
				$ret['message'] = 'Success';
				$ret['data'] = $result;
			} else {
				$ret['code'] = 200;
				$ret['message'] = '暂无商品类别信息';
			}

			Db::commit();
			return json($ret);
		} catch (PDOException $e) {
			Db::rollback();
			$ret['code'] = 201;
			$ret['message'] = 'Fail' . $e;
			return json($ret);
		}
	}

	// 获得某个产品
	public function getProductById()
	{
		$prefix = "https://" . $_SERVER['SERVER_NAME'] . ":" . $_SERVER["SERVER_PORT"];

		$params = $this->request->param();
		$id = isset($params["id"]) ? $params["id"] : "";

		try {
			$sql = "
			SELECT id, category_id, specs_id, manufactor_id, role_id, merchant_id,
				product_name, brand, unit, amount,
				REPLACE(hd_product.small_image,'/uploads','{$prefix}/uploads') as small_image ,
				REPLACE(hd_product.product_images,'/uploads','{$prefix}/uploads') as product_images ,
				market_price, sale_price, status, is_hot, brief_introduction, detail_introduction,
				clinic_share, SGS_share, recommender_share, create_time, comments
			FROM
				hd_product
			where id = '$id';
			";
			$result = Db::query($sql);
			if (count($result) != 0) {
				$ret['code'] = 200;
				$ret['message'] = 'Success';
				$ret['data'] = $result;
			} else {
				$ret['code'] = 200;
				$ret['message'] = '暂无产品信息';
			}

			Db::commit();
			return json($ret);
		} catch (PDOException $e) {
			Db::rollback();
			$ret['code'] = 201;
			$ret['message'] = 'Fail' . $e;
			return json($ret);
		}
	}

	// 获得某分类下的产品
	public function getProductsByCategoryId()
	{
		$prefix = "https://" . $_SERVER['SERVER_NAME'] . ":" . $_SERVER["SERVER_PORT"];

		$params = $this->request->param();
		$id = isset($params["id"]) ? $params["id"] : "";

		try {
			$sql = "
			SELECT id, category_id, specs_id, manufactor_id, role_id, merchant_id,
				product_name, brand, unit, amount,
				REPLACE(hd_product.small_image,'/uploads','{$prefix}/uploads') as small_image ,
				REPLACE(hd_product.product_images,'/uploads','{$prefix}/uploads') as product_images ,
				market_price, sale_price, status, is_hot, brief_introduction, detail_introduction,
				clinic_share, SGS_share, recommender_share, create_time, comments
			FROM
				hd_product
			where category_id = '{$id}';
			";
			$result = Db::query($sql);
			if (count($result) != 0) {
				$ret['code'] = 200;
				$ret['message'] = 'Success';
				$ret['data'] = $result;
			} else {
				$ret['code'] = 200;
				$ret['message'] = '暂无产品信息';
			}

			Db::commit();
			return json($ret);
		} catch (PDOException $e) {
			Db::rollback();
			$ret['code'] = 201;
			$ret['message'] = 'Fail' . $e;
			return json($ret);
		}
	}

	//获取分类表 所有信息
	public function getCategory()
	{
		Db::startTrans();
		try {
			$sql = "select * from  hd_category";
			$result = Db::query($sql);
			if (count($result) != 0) {
				$ret['code'] = 200;
				$ret['message'] = 'Success';
				$ret['data'] = $result;
			} else {
				$ret['code'] = 200;
				$ret['message'] = '暂无产品类别信息';
			}

			Db::commit();
			return json($ret);
		} catch (PDOException $e) {
			Db::rollback();
			$ret['code'] = 201;
			$ret['message'] = 'Fail' . $e;
			return json($ret);
		}
	}

	// 热门产品
	public function getHotProduct()
	{
		$prefix = "https://" . $_SERVER['SERVER_NAME'] . ":" . $_SERVER["SERVER_PORT"];

		Db::startTrans();
		try {
			$sql = "select images from  hd_param where param = '轮播图'";
			$swiperRes = Db::query($sql);
			$swiperImages = explode(',', $swiperRes[0]["images"]);
			for ($j = 0; $j < count($swiperImages); $j++) {
				$swiperImages[$j] = $prefix . $swiperImages[$j];
			}
			$swiperImages = implode(',', $swiperImages);

			$sql = "select * from  hd_product where is_hot='1'";
			$result = Db::query($sql);

			for ($i = 0; $i < count($result); $i++) {
				$result[$i]["small_image"] = $prefix . $result[$i]["small_image"];

				$productImags = explode(',', $result[$i]["product_images"]);
				for ($j = 0; $j < count($productImags); $j++) {
					$productImags[$j] = $prefix . $productImags[$j];
				}
				$productImags = implode(',', $productImags);
				$result[$i]["product_images"] = $productImags;
			}

			// 小程序审核开关
			$sql = "select paramvalue from hd_param where param = '小程序审核开关'";
			$paramRes = Db::query($sql);

			if (count($result) != 0) {
				$ret['code'] = 200;
				$ret['message'] = 'Success';
				$ret['data'] = $result;
			} else {
				$ret['code'] = 200;
				$ret['message'] = '暂无热门产品';
			}
			$ret['swiperImages'] = $swiperImages;
			$ret['verifyOn'] = $paramRes[0]["paramvalue"];
			Db::commit();
			return json($ret);
		} catch (PDOException $e) {
			Db::rollback();
			$ret['code'] = 201;
			$ret['message'] = 'Fail' . $e;
			return json($ret);
		}
	}

	//------------------------------------------------------------------资讯类--------------------------------------------------------
	// 获取指标意义
	public function getQuota()
	{
		$prefix = "https://" . $_SERVER['SERVER_NAME'] . ":" . $_SERVER["SERVER_PORT"];

		Db::startTrans();
		try {
			$sql = "select id, quota_name,REPLACE(hd_quota.descript," .  "'<img src=\"'," . "'<img src=\"" . $prefix . "') as descript " . "from hd_quota ";
			$result = Db::query($sql);
			if (count($result) != 0) {
				$ret['code'] = 200;
				$ret['message'] = 'Success';
				$ret['data'] = $result;
			} else {
				$ret['code'] = 200;
				$ret['message'] = '暂无指标信息';
			}

			Db::commit();
			return json($ret);
		} catch (PDOException $e) {
			Db::rollback();
			$ret['code'] = 201;
			$ret['message'] = 'Fail' . $e;
			return json($ret);
		}
	}

	//获取资讯列表
	public function getHealthInfo()
	{
		$prefix = "https://" . $_SERVER['SERVER_NAME'] . ":" . $_SERVER["SERVER_PORT"];

		Db::startTrans();
		try {
			// $sql = "select * from  hd_health_info";
			$sql = "select id, title,author,create_time,
				REPLACE(hd_health_info.image,'/uploads','{$prefix}/uploads') as image ," .
				"REPLACE(hd_health_info.content," .  "'<img src=\"'," . "'<img src=\"" . $prefix . "') as content " .
				"from hd_health_info ";

			$result = Db::query($sql);
			if (count($result) != 0) {
				$ret['code'] = 200;
				$ret['message'] = 'Success';
				$ret['data'] = $result;
			} else {
				$ret['code'] = 200;
				$ret['message'] = '暂无资讯信息';
			}

			Db::commit();
			return json($ret);
		} catch (PDOException $e) {
			Db::rollback();
			$ret['code'] = 201;
			$ret['message'] = 'Fail' . $e;
			return json($ret);
		}
	}

	//-------------------------------------------------------------------购物车--------------------------------------------------------

	// 加入购物车
	public function addCart()
	{
		$params = $this->request->param();
		$openid = isset($params["openid"]) ? $params["openid"] : "";
		$productId = isset($params["productId"]) ? $params["productId"] : "";

		$res = $this->checkOpenid($openid);

		if ($res["code"] != 200) {
			$ret['code'] = 201;
			$ret['message'] = '无权限操作';
			return json($ret);
		}

		Db::startTrans();
		try {
			$uid = $res["data"][0]["m_no"];

			$sql = "select * from hd_cart where pid='{$productId}'";
			$result = Db::query($sql);
			// 若已有商品，则更新记录 number = number+1
			if (count($result) != 0) {
				$number = $result[0]["number"] + 1;
				$sql = "update hd_cart set uid='{$uid}', pid='{$productId}', number='{$number}' where pid='{$productId}'";
			} else {  // 没有该商品，直接插入 ,number=1
				$sql = "insert into hd_cart (uid,pid,number) values ('{$uid}','{$productId}',1)";
			}

			$result = Db::execute($sql);
			if ($result != 0) {
				$ret['code'] = 200;
				$ret['message'] = 'Success';
				$ret['data'] = $result;
			} else {
				$ret['code'] = 200;
				$ret['message'] = '无影响记录';
				$ret['data'] = $result;
			}

			Db::commit();
			return json($ret);
		} catch (PDOException $e) {
			Db::rollback();
			$ret['code'] = 201;
			$ret['message'] = 'Fail' . $e;
			return json($ret);
		}
	}

	// 获取购物车 列表
	public function getCartList()
	{
		$prefix = "https://" . $_SERVER['SERVER_NAME'] . ":" . $_SERVER["SERVER_PORT"];

		$params = $this->request->param();
		$openid = isset($params["openid"]) ? $params["openid"] : "";

		$res = $this->checkOpenid($openid);

		if ($res["code"] != 200) {
			$ret['code'] = 201;
			$ret['message'] = '无权限操作';
			return json($ret);
		}

		Db::startTrans();
		try {
			$uid = $res["data"][0]["m_no"];

			$sql = "SELECT
				hd_cart.id,
				hd_cart.uid,
				hd_cart.pid,
				hd_cart.number,
				hd_cart.createtime,
				hd_member.m_no,
				hd_member.real_name,
				hd_product.id,
				hd_product.product_name,
				hd_product.brand,
				-- hd_product.small_image,
				REPLACE(hd_product.small_image,'/uploads','{$prefix}/uploads') as small_image ,
				hd_product.market_price,
				hd_product.sale_price,
				hd_product.brief_introduction,
				hd_product.detail_introduction
				FROM
				hd_cart
				LEFT JOIN hd_member ON hd_cart.uid = hd_member.m_no
				LEFT JOIN hd_product ON hd_cart.pid = hd_product.id 
				where uid = '{$uid}'";

			$result = Db::query($sql);
			if (count($result) != 0) {
				$ret['code'] = 200;
				$ret['message'] = 'Success';
				$ret['data'] = $result;
			} else {
				$ret['code'] = 200;
				$ret['message'] = '购物车是空的';
				$ret['data'] = $result;
			}

			Db::commit();
			return json($ret);
		} catch (PDOException $e) {
			Db::rollback();
			$ret['code'] = 201;
			$ret['message'] = 'Fail' . $e;
			return json($ret);
		}
	}

	// 从购物车中删除 某条商品
	public function removeCartById()
	{
		$params = $this->request->param();
		$openid = isset($params["openid"]) ? $params["openid"] : "";
		$productId = isset($params["productId"]) ? $params["productId"] : "";

		$res = $this->checkOpenid($openid);

		if ($res["code"] != 200) {
			$ret['code'] = 201;
			$ret['message'] = '无权限操作';
			return json($ret);
		}

		Db::startTrans();
		try {
			$uid = $res["data"][0]["m_no"];

			$sql = "delete from hd_cart where uid={$uid} and pid='{$productId}'";
			$result = Db::execute($sql);
			if ($result != 0) {
				$ret['code'] = 200;
				$ret['message'] = 'Success';
				$ret['data'] = $result;
			} else {  // 无记录可删
				$ret['code'] = 200;
				$ret['message'] = '无记录可删';
				$ret['data'] = $result;
			}

			Db::commit();
			return json($ret);
		} catch (PDOException $e) {
			Db::rollback();
			$ret['code'] = 201;
			$ret['message'] = 'Fail' . $e;
			return json($ret);
		}
	}

	// 批量删除 购物车中的商品
	private function clearCartByIds($pIds, $uid)
	{
		Db::startTrans();
		try {
			$sql = "delete from hd_cart where uid={$uid} and find_in_set(pid,'{$pIds}')";
			$result = Db::execute($sql);
			if ($result != 0) {
				$ret['code'] = 200;
				$ret['message'] = 'Success';
				$ret['data'] = $result;
			} else {  // 无记录可删
				$ret['code'] = 200;
				$ret['message'] = '无记录可删';
				$ret['data'] = $result;
			}

			Db::commit();
			return json($ret);
		} catch (PDOException $e) {
			Db::rollback();
			$ret['code'] = 201;
			$ret['message'] = 'Fail' . $e;
			return json($ret);
		}
	}

	// 批量删除 购物车中的商品
	public function removeCartByIds()
	{
		$params = $this->request->param();
		$openid = isset($params["openid"]) ? $params["openid"] : "";
		$productIds = isset($params["productIds"]) ? $params["productIds"] : "";

		$res = $this->checkOpenid($openid);

		if ($res["code"] != 200) {
			$ret['code'] = 201;
			$ret['message'] = '无权限操作';
			return json($ret);
		}

		Db::startTrans();
		try {
			$uid = $res["data"][0]["m_no"];

			$sql = "delete from hd_cart where uid={$uid} and pid in '{$productIds}'";
			$result = Db::execute($sql);
			if ($result != 0) {
				$ret['code'] = 200;
				$ret['message'] = 'Success';
				$ret['data'] = $result;
			} else {  // 无记录可删
				$ret['code'] = 200;
				$ret['message'] = '无记录可删';
				$ret['data'] = $result;
			}

			Db::commit();
			return json($ret);
		} catch (PDOException $e) {
			Db::rollback();
			$ret['code'] = 201;
			$ret['message'] = 'Fail' . $e;
			return json($ret);
		}
	}

	// 清空购物车
	public function clearCart()
	{
		$params = $this->request->param();
		$openid = isset($params["openid"]) ? $params["openid"] : "";

		$res = $this->checkOpenid($openid);

		if ($res["code"] != 200) {
			$ret['code'] = 201;
			$ret['message'] = '无权限操作';
			return json($ret);
		}

		Db::startTrans();
		try {
			$uid = $res["data"][0]["m_no"];

			$sql = "delete from hd_cart where uid={$uid} ";
			$result = Db::execute($sql);
			if ($result != 0) {
				$ret['code'] = 200;
				$ret['message'] = 'Success';
				$ret['data'] = $result;
			} else {  // 无记录可删
				$ret['code'] = 200;
				$ret['message'] = '无记录可删';
				$ret['data'] = $result;
			}

			Db::commit();
			return json($ret);
		} catch (PDOException $e) {
			Db::rollback();
			$ret['code'] = 201;
			$ret['message'] = 'Fail' . $e;
			return json($ret);
		}
	}

	//-------------------------------------------------------------------订单--------------------------------------------------------

	// 创建订单
	// ---暂时只有一个功能：返回用户的默认地址
	public function createOrder()
	{
		$params = $this->request->param();
		$openid = isset($params["openid"]) ? $params["openid"] : "";

		$res = $this->checkOpenid($openid);

		if ($res["code"] != 200) {
			$ret['code'] = 201;
			$ret['message'] = '无权限操作';
			return json($ret);
		}

		try {
			// 获得会员的默认收货地址
			$sql = "select * from hd_address where openid='$openid' and isdefault='1' ";
			$result = Db::query($sql);
			if (count($result) != 0) {
				$address = $result[0];
				$ret["data"]["address"] = $address;
				$ret["code"] = 200;
				$ret["message"] = "Success";
			} else {
				$ret["code"] = 201;
				$ret["message"] = "无默认收货地址";
			}

			return json($ret);
		} catch (PDOException $e) {
			$ret['code'] = 201;
			$ret['message'] = 'Fail' . $e;
			return json($ret);
		}
	}

	// 医生下单
	public function saveDoctorOrder()
	{
		$params = $this->request->param();
		$doctorId = isset($params["openid"]) ? $params["openid"] : ""; // openid是医生的，对应hd_order表的doctor_id字段

		$checkRes = $this->checkOpenid($doctorId);
		if ($checkRes["code"] != 200) {
			$ret['code'] = 201;
			$ret['message'] = '无权限操作';
			return json($ret);
		}
		$memberId = $checkRes["data"][0]["m_no"]; // 记录下单用户ID

		$params = $params["orderdata"];
		$address = isset($params["addressdata"]) ? $params["addressdata"] : ""; // 诊所地址
		$goods = isset($params["goodsdata"]) ? $params["goodsdata"] : "";
		$comments = isset($params["comments"]) ? $params["comments"] : "";
		$type = "exam";
		$payChannel = isset($params["payChannel"]) ? $params["payChannel"] : "";
		$orderNum = build_order_num();
		$status = "待支付";
		$totalPrice = isset($params["total"]) ? $params["total"] : 0;

		Db::startTrans();
		try {
			$clinicId = $address["merchant_id"];
			$clinicName = $address["merchant_name"];
			$clinicMobile = $address["merchant_tel"];
			$clinicAddress = $address["address"];
			// --插入订单表
			$sql = "insert into hd_order(number,type,status,doctor_id,clinic_id,clinic_name,clinic_mobile,clinic_address,total_price,comments,pay_channel) 
					values('$orderNum','$type','$status','$doctorId',$clinicId,'$clinicName','$clinicMobile','$clinicAddress',$totalPrice,'$comments','$payChannel')";
			$orderRes = Db::execute($sql);

			// --插入订单详情表
			for ($i = 0; $i < count($goods); $i++) {
				$products = $goods[$i]["productData"];
				$merchantId =  $goods[$i]["merchantID"];
				for ($j = 0; $j < count($products); $j++) {
					$product = $products[$j];
					$productId = $product["id"];
					$productName = $product["product_name"];
					$brand = $product["brand"];
					$amount = isset($product["number"]) ? $product["number"] : 1;

					$sql = "insert into hd_order_detail(orders_no,product_id,member_id,merchant_id,product_name,brand,amount) 
							values('$orderNum','$productId','$memberId','$merchantId','$productName','$brand' ,'$amount')";   // memberId
					$orderDetailRes = Db::execute($sql);
				}
			}

			$ret["code"] = 200;
			$ret["message"] = "Success";
			$ret["order_num"] = $orderNum;

			Db::commit();
			return json($ret);
		} catch (PDOException $e) {
			Db::rollback();
			$ret['code'] = 201;
			$ret['message'] = 'Fail' . $e;
			return json($ret);
		}
	}

	// 体检套餐下单
	public function savePackageOrder()
	{
		$params = $this->request->param();
		$openid = isset($params["openid"]) ? $params["openid"] : ""; // openid是医生的，对应hd_order表的doctor_id字段

		$checkRes = $this->checkOpenid($openid);
		if ($checkRes["code"] != 200) {
			$ret['code'] = 201;
			$ret['message'] = '无权限操作';
			return json($ret);
		}
		$memberId = $checkRes["data"][0]["m_no"]; // 记录下单用户ID

		$params = $params["orderdata"];
		$product = isset($params["goodsdata"]) ? $params["goodsdata"] : "";
		$type = isset($params["type"]) ? $params["type"] : "";
		$payChannel = isset($params["payChannel"]) ? $params["payChannel"] : "";
		$orderNum = build_order_num();
		$status = "待支付";
		$totalPrice = isset($params["total"]) ? $params["total"] : 0;

		Db::startTrans();
		try {
			// --插入订单表
			$orderSql = "insert into hd_order(number,type,status,openid,total_price,pay_channel) 
					values('$orderNum','$type','$status','$openid',$totalPrice,'$payChannel')";
			$orderRes = Db::execute($orderSql);

			// --插入订单详情表
			$productId = $product["id"];
			$merchantId = $product["merchant_id"];
			$productName = $product["product_name"];
			$sql = "insert into hd_order_detail(orders_no,product_id,member_id,merchant_id,product_name,amount) 
					values('$orderNum','$productId','$memberId','$merchantId','$productName',1)";   // memberId
			$orderDetailRes = Db::execute($sql);

			$ret["code"] = 200;
			$ret["message"] = "Success";
			$ret["order_num"] = $orderNum;

			Db::commit();
			return json($ret);
		} catch (PDOException $e) {
			Db::rollback();
			$ret['code'] = 201;
			$ret['message'] = 'Fail' . $e;
			return json($ret);
		}
	}

	// 提交订单（自主下单+商城下单）   -- 订单表、订单详情表 均需插入记录
	public function saveOrder()
	{
		$params = $this->request->param();
		$openid = isset($params["openid"]) ? $params["openid"] : "";

		$checkRes = $this->checkOpenid($openid);
		if ($checkRes["code"] != 200) {
			$ret['code'] = 201;
			$ret['message'] = '无权限操作';
			return json($ret);
		}
		$memberId = $checkRes["data"][0]["m_no"]; // 记录用户ID
		$params = $params["orderdata"];

		$orderNum = build_order_num();
		$status = "待支付";
		$totalPrice = isset($params["total"]) ? $params["total"] : 0;
		$address = isset($params["addressdata"]) ? $params["addressdata"] : "";
		$goods = isset($params["goodsdata"]) ? $params["goodsdata"] : "";
		$comments = isset($params["comments"]) ? $params["comments"] : "";
		$type = isset($params["type"]) ? $params["type"] : "";
		$payChannel = isset($params["payChannel"]) ? $params["payChannel"] : "";
		if ($type == "shop") {		// 提交的是商城里的订单时
			Db::startTrans();
			try {
				$memberName = $address["user_name"];
				$memberMobile = $address["user_mobile"];
				$memberAddress = $address["city"] . $address["address"] . $address["detail_address"];
				// --插入订单表
				$sql = "insert into hd_order(number,	type,	status,		openid,	member_name,member_mobile,	member_address,total_price,comments,pay_channel) 
									values('$orderNum','$type','$status','$openid','$memberName','$memberMobile','$memberAddress',$totalPrice,'$comments','$payChannel')";
				$orderRes = Db::execute($sql);

				// --插入订单详情表
				$productIds = array(); // 记录商品ID，用于删除购物车里的商品
				for ($i = 0; $i < count($goods); $i++) {
					$product = $goods[$i];

					$productId = $product["pid"];
					$productName = $product["product_name"];
					$brand = $product["brand"];
					$amount = $product["number"];

					array_push($productIds, $productId);

					$sql = "insert into hd_order_detail(orders_no,product_id,member_id,product_name,brand,amount) 
						values('$orderNum','$productId','$memberId','$productName','$brand' ,'$amount')";
					$orderDetailRes = Db::execute($sql);
				}

				// --删除购物车里面已提交的商品
				$pIds = implode(",", $productIds);
				$this->clearCartByIds($pIds, $memberId);

				$ret["code"] = 200;
				$ret["message"] = "Success";
				$ret["order_num"] = $orderNum;

				Db::commit();
				return json($ret);
			} catch (PDOException $e) {
				Db::rollback();
				$ret['code'] = 201;
				$ret['message'] = 'Fail' . $e;
				return json($ret);
			}
		} elseif ($type == "detect") { // 提交的是检测订单时
			Db::startTrans();
			try {
				$clinicId = $address["merchant_id"];
				$clinicName = $address["merchant_name"];
				$clinicMobile = $address["merchant_tel"];
				$clinicAddress = $address["address"];
				// --插入订单表
				$sql = "insert into hd_order(number,	type,	status,	openid,		clinic_id,clinic_name,clinic_mobile,clinic_address,total_price,comments,pay_channel) 
									values('$orderNum','$type','$status','$openid',	$clinicId,'$clinicName','$clinicMobile','$clinicAddress',$totalPrice,'$comments','$payChannel')";
				$orderRes = Db::execute($sql);

				// --插入订单详情表
				for ($i = 0; $i < count($goods); $i++) {
					$products = $goods[$i]["productData"];
					$merchantId =  $goods[$i]["merchantID"];
					for ($j = 0; $j < count($products); $j++) {
						$product = $products[$j];
						$productId = $product["id"];
						$productName = $product["product_name"];
						$brand = $product["brand"];
						$amount = isset($product["number"]) ? $product["number"] : 1;

						$sql = "insert into hd_order_detail(orders_no,product_id,member_id,merchant_id,product_name,brand,amount) 
							values('$orderNum','$productId','$memberId','$merchantId','$productName','$brand' ,'$amount')";
						$orderDetailRes = Db::execute($sql);
					}
				}

				$ret["code"] = 200;
				$ret["message"] = "Success";
				$ret["order_num"] = $orderNum;

				Db::commit();
				return json($ret);
			} catch (PDOException $e) {
				Db::rollback();
				$ret['code'] = 201;
				$ret['message'] = 'Fail' . $e;
				return json($ret);
			}
		} else {  // 订单类型错误，不是{shop,detect}
			$ret['code'] = 201;
			$ret['message'] = '订单类型错误';
			return json($ret);
		}
	}

	// 获取用户帐单
	public function getUserBill()
	{
		$params = $this->request->param();
		$openid = isset($params["openid"]) ? $params["openid"] : "";
		$memberNo = isset($params["memberNo"]) ? $params["memberNo"] : "";

		$res = $this->checkOpenid($openid);
		if ($res["code"] != 200) {
			$ret['code'] = 201;
			$ret['message'] = '无权限操作';
			return json($ret);
		}
		try {
			$sql = "select hd_member_bill.*,hd_member.balance
			from hd_member_bill 
			LEFT JOIN hd_member  ON hd_member_bill.member_no = hd_member.m_no
			where member_no='$memberNo'";
			$result = Db::query($sql);
			$ret["code"] = 200;
			$ret["message"] = "Success";
			$ret["billdata"] = $result;
			$ret["balance"] = $result[0]["balance"];

			return json($ret);
		} catch (PDOException $e) {
			$ret["code"] = 201;
			$ret['message'] = 'Fail' . $e;
			return json($ret);
		}
	}

	// 我的推荐
	public function getMyRecmmend()
	{
		$params = $this->request->param();
		$openid = isset($params["openid"]) ? $params["openid"] : "";

		$res = $this->checkOpenid($openid);
		if ($res["code"] != 200) {
			$ret['code'] = 201;
			$ret['message'] = '无权限操作';
			return json($ret);
		}

		try {
			$sql = "select *
			from hd_member
			where recommender_id='$openid'";
			$result = Db::query($sql);

			$ret["code"] = 200;
			$ret["message"] = "Success";
			$ret["recdata"] = $result;
			return json($ret);
		} catch (PDOException $e) {
			$ret["code"] = 201;
			$ret['message'] = 'Fail' . $e;
			return json($ret);
		}
	}

	// 获取用户订单
	public function getOrders()
	{
		$params = $this->request->param();
		$openid = isset($params["openid"]) ? $params["openid"] : "";

		$memberRes = $this->checkOpenid($openid);
		if ($memberRes["code"] != 200) {
			$ret['code'] = 201;
			$ret['message'] = '无权限操作';
			return json($ret);
		}

		try {
			$sql = "select * from hd_order where openid='$openid' or doctor_id='$openid' order by id desc";
			$orderRes = Db::query($sql);

			if (count($orderRes) != 0) {
				for ($i = 0; $i < count($orderRes); $i++) {
					$order = $orderRes[$i];

					$res[$i]["orderNum"] = $order["number"];
					$res[$i]["status"] = $order["status"];
					$res[$i]["type"] = $order["type"];
					$res[$i]["total"] = $order["total_price"];
					$res[$i]["createTime"] = $order["createtime"];
					$res[$i]["doctorId"] = isset($order["doctor_id"]) ? $order["doctor_id"] : "";
					$res[$i]["detail"] = $this->orderDetail($order["number"], $order["type"]);
				}

				$ret["code"] = 200;
				$ret["message"] = "Success";
				$ret["data"] = $res;
				return json($ret);
			} else {
				$ret["code"] = 200;
				$ret["message"] = "暂无订单";

				return json($ret);
			}
		} catch (PDOException $e) {
			$ret['code'] = 201;
			$ret['message'] = 'Fail' . $e;
			return json($ret);
		}
	}

	private function orderDetail($orderNum, $orderType)
	{
		$prefix = "https://" . $_SERVER['SERVER_NAME'] . ":" . $_SERVER["SERVER_PORT"];
		$ret = [];

		if ($orderType == "shop") {
			$sql = "SELECT
				hd_order_detail.*,
				REPLACE(hd_product.small_image,'/uploads','$prefix/uploads') as small_image ,
				REPLACE(hd_product.product_images,'/uploads','$prefix/uploads') as product_images ,
				hd_product.market_price,
				hd_product.sale_price,
				hd_product.brief_introduction,
				REPLACE(hd_product.detail_introduction," .  "'<img src=\"'," . "'<img src=\"" . $prefix . "') as descript,
				hd_merchant.merchant_id as merchantID,
				hd_merchant.merchant_name,
				hd_merchant.merchant_type,
				hd_merchant.pay_rider,
				hd_merchant.address,
				REPLACE(hd_merchant.merchant_image,'/uploads','$prefix/uploads') as merchant_image ,
				hd_merchant.merchant_tel,
				hd_member.m_no,
				hd_member.real_name,
				hd_member.nick_name,
				hd_member.id_card,
				hd_member.gender,
				hd_member.mobile
				FROM
				hd_order_detail
				LEFT JOIN hd_product ON hd_order_detail.product_id = hd_product.id
				LEFT JOIN hd_member ON hd_order_detail.member_id = hd_member.m_no
				LEFT JOIN hd_merchant ON hd_order_detail.merchant_id = hd_merchant.merchant_id
				WHERE orders_no='$orderNum' ";
			$orderDetailRes = Db::query($sql);
			$ret["data"] = $orderDetailRes;
		} else {
			$sql = "SELECT
				hd_order_detail.id,
				hd_product.id as productID,
				hd_merchant.merchant_id as merchantID,
				hd_merchant.merchant_name as merchantName,
				hd_member.m_no
				FROM
				hd_order_detail
				LEFT JOIN hd_product ON hd_order_detail.product_id = hd_product.id
				LEFT JOIN hd_member ON hd_order_detail.member_id = hd_member.m_no
				LEFT JOIN hd_merchant ON hd_order_detail.merchant_id = hd_merchant.merchant_id
				WHERE orders_no='$orderNum'
				GROUP BY merchantID";
			$groupRes = Db::query($sql);

			for ($i = 0; $i < count($groupRes); $i++) {
				$merchantId = $groupRes[$i]["merchantID"];
				$merchantName = $groupRes[$i]["merchantName"];

				$sql = "SELECT
				hd_order_detail.*,
				REPLACE(hd_product.small_image,'/uploads','$prefix/uploads') as small_image ,
				REPLACE(hd_product.product_images,'/uploads','$prefix/uploads') as product_images ,
				hd_product.market_price,
				hd_product.sale_price,
				hd_product.brief_introduction,
				REPLACE(hd_product.detail_introduction," .  "'<img src=\"'," . "'<img src=\"" . $prefix . "') as descript,
				hd_merchant.merchant_id as merchantID,
				hd_merchant.merchant_name,
				hd_merchant.merchant_type,
				hd_merchant.pay_rider,
				hd_merchant.address,
				REPLACE(hd_merchant.merchant_image,'/uploads','$prefix/uploads') as merchant_image ,
				hd_merchant.merchant_tel,
				hd_member.m_no,
				hd_member.real_name,
				hd_member.nick_name,
				hd_member.id_card,
				hd_member.gender,
				hd_member.mobile
				FROM
				hd_order_detail
				LEFT JOIN hd_product ON hd_order_detail.product_id = hd_product.id
				LEFT JOIN hd_member ON hd_order_detail.member_id = hd_member.m_no
				LEFT JOIN hd_merchant ON hd_order_detail.merchant_id = hd_merchant.merchant_id
				WHERE orders_no='$orderNum' AND hd_merchant.merchant_id='$merchantId'  ";

				$orderDetailRes = Db::query($sql);
				$ret[$i]["merchantName"] = $merchantName;
				$ret[$i]["data"] = $orderDetailRes;
			}
		}

		return $ret;
	}

	// 获得医生下单的订单详情
	public function getDoctorOrderDetail()
	{
		$params = $this->request->param();
		$openid = isset($params["openid"]) ? $params["openid"] : "";  //

		$res = $this->checkOpenid($openid);
		if ($res["code"] != 200) {
			$ret['code'] = 201;
			$ret['message'] = '无权限操作';
			return json($ret);
		}

		$orderNum = isset($params["order_id"]) ? $params["order_id"] : "";
		$recOpenid = isset($params["recOpenid"]) ? $params["recOpenid"] : "";
		$orderType = isset($params["type"]) ? $params["type"] : "";
		Db::startTrans();
		try {
			// --更新用户表（若recommender_id为空，就写入医生的openid；不为空就不操作）
			$sql = "update hd_member set recommender_id='$recOpenid' where openid='$openid' and isnull(recommender_id)";
			Db::execute($sql);

			// --更新订单表（扫码，将用户openid更新到订单表）
			$sql = "update hd_order set openid='$openid' where number = '$orderNum' and isnull(openid)";
			Db::execute($sql);

			// --返回用户信息
			$sql = "select *, (SELECT  TIMESTAMPDIFF(YEAR,(select birthday from hd_member where openid='$openid'), CURDATE()) )AS age from hd_member where openid='$openid'";
			$userRes = Db::query($sql);

			// --返回下单医生信息
			$sql = "select * from hd_member where openid='$recOpenid' ";
			$doctorRes = Db::query($sql);

			// --返回订单详情
			$sql = "select * from hd_order where number='$orderNum'";
			$orderRes = Db::query($sql);
			$orderDetailRes = $this->orderDetail($orderNum, $orderType);

			Db::commit();
			$ret["code"] = 200;
			$ret["message"] = "Success";
			$ret["userData"] = $userRes;
			$ret["doctor"] = $doctorRes;
			$ret["orderData"] = $orderRes;
			$ret["orderDetailData"] = $orderDetailRes;

			return json($ret);
		} catch (PDOException $e) {
			Db::rollback();
			$ret["code"] = 201;
			$ret['message'] = 'Fail' . $e;
			return json($ret);
		}
	}

	// 获取某个订单详情
	public function getOrderDetail()
	{
		$params = $this->request->param();
		$openid = isset($params["openid"]) ? $params["openid"] : "";

		$res = $this->checkOpenid($openid);
		if ($res["code"] != 200) {
			$ret['code'] = 201;
			$ret['message'] = '无权限操作';
			return json($ret);
		}

		$orderNum = isset($params["order_id"]) ? $params["order_id"] : "";
		$orderType = isset($params["type"]) ? $params["type"] : "";
		try {
			$sql = "select * from hd_order where number='$orderNum'";
			$orderRes = Db::query($sql);
			$orderDetailRes = $this->orderDetail($orderNum, $orderType);

			$ret["code"] = 200;
			$ret["message"] = "Success";
			$ret["orderData"] = $orderRes;
			$ret["orderDetailData"] = $orderDetailRes;

			return json($ret);
		} catch (PDOException $e) {
			$ret["code"] = 201;
			$ret['message'] = 'Fail' . $e;
			return json($ret);
		}
	}

	// 删除订单
	public function deleteOrder()
	{
	}
	// 获得打印数据
	public function getOrderPrint()
	{
		$params = $this->request->param();
		$openid = isset($params["openid"]) ? $params["openid"] : "";

		$memberRes = $this->checkOpenid($openid);
		if ($memberRes["code"] != 200) {
			$ret['code'] = 201;
			$ret['message'] = '无权限操作';
			return json($ret);
		}
		$orderNum = isset($params["orderNum"]) ? $params["orderNum"] : "";
		try {
			$sql = "SELECT
			hd_order_detail.id,
			hd_product.id as productID,
			hd_merchant.merchant_id as merchantID,
			hd_merchant.merchant_name as merchantName
			FROM
			hd_order_detail
			LEFT JOIN hd_product ON hd_order_detail.product_id = hd_product.id
			LEFT JOIN hd_merchant ON hd_order_detail.merchant_id = hd_merchant.merchant_id
			WHERE orders_no='{$orderNum}'
			GROUP BY merchantID";
			$merchantRes = Db::query($sql);
			$ret = [];
			// $ret["user"] = $memberRes;
			for ($i = 0; $i < count($merchantRes); $i++) {
				$sql = "SELECT hd_order_detail.*,
				hd_product.market_price,
				GROUP_CONCAT(hd_product.product_name) as productNames,
				hd_product.item_type,
				hd_order.clinic_name,
				hd_merchant.merchant_id as merchantID,
				hd_merchant.merchant_tel,
				hd_merchant.merchant_abbr,
				hd_member.real_name,
				hd_member.gender
				FROM
				hd_order_detail
				LEFT JOIN hd_product ON hd_order_detail.product_id = hd_product.id
				LEFT JOIN hd_member ON hd_order_detail.member_id = hd_member.m_no
				LEFT JOIN hd_order ON hd_order_detail.orders_no = hd_order.number
				LEFT JOIN hd_merchant ON hd_order_detail.merchant_id = hd_merchant.merchant_id
				WHERE orders_no = '$orderNum' and hd_merchant.merchant_id = '{$merchantRes[$i]["merchantID"]}'
				GROUP BY hd_product.item_type
				";
				$productRes = Db::query($sql);
				$ret["merchantData"][$i] = $merchantRes[$i];
				$ret["merchantData"][$i]["productData"] = $productRes;
				$ret["merchantData"][$i]["age"] = $memberRes["data"][0]["age"];
			}

			$ret["code"] = 200;
			$ret["message"] = "Success";

			return json($ret);
		} catch (PDOException $e) {
			$ret["code"] = 201;
			$ret['message'] = 'Fail' . $e;
			return json($ret);
		}
	}

	// 获得 检测报告
	public function getReport()
	{
		$prefix = "https://" . $_SERVER['SERVER_NAME'] . ":" . $_SERVER["SERVER_PORT"];

		$params = $this->request->param();
		$openid = isset($params["openid"]) ? $params["openid"] : "";

		$memberRes = $this->checkOpenid($openid);
		if ($memberRes["code"] != 200) {
			$ret['code'] = 201;
			$ret['message'] = '无权限操作';
			return json($ret);
		}

		try {
			$source = isset($params["source"]) ? $params["source"] : "";

			if ($source == '0') {
				$sql = "select number ,type,REPLACE(hd_order.detect_report,'/uploads','$prefix/uploads') as detectReport ,detectedtime
				from hd_order where (openid='$openid' or doctor_id='$openid') and detect_report is not null";
			} else if ($source == '2') {
				$sql = "select number ,type,REPLACE(hd_order.detect_report,'/uploads','$prefix/uploads') as detectReport ,detectedtime
				from hd_order where type = 'package' and (openid='$openid' or doctor_id='$openid') and detect_report is not null";
			} else {
				$sql = "select number ,type,REPLACE(hd_order.detect_report,'/uploads','$prefix/uploads') as detectReport ,detectedtime
				from hd_order where type != 'package' and (openid='$openid' or doctor_id='$openid') and detect_report is not null";
			}

			$reportRes = Db::query($sql);
			$ret = [];
			// $ret["user"] = $memberRes;
			for ($i = 0; $i < count($reportRes); $i++) {
				$report = $reportRes[$i];
				$orderNum = $report["number"];

				$sql = "select product_name from hd_order_detail where orders_no='$orderNum'";
				$nameRes = Db::query($sql);
				$productNames = [];
				foreach ($nameRes as $name) {
					array_push($productNames, $name["product_name"]);
				}
				$productNames = implode(",", $productNames);

				$ret["data"][$i]["orderNum"] = $orderNum;
				$ret["data"][$i]["user"] = $memberRes["data"];
				$ret["data"][$i]["detectedTime"] = $report["detectedtime"];
				$ret["data"][$i]["detectReport"] = $report["detectReport"];
				$ret["data"][$i]["type"] = $report["type"];
				$ret["data"][$i]["productNames"] = $productNames;
			}

			$ret["code"] = 200;
			$ret["message"] = "Success";

			return json($ret);
		} catch (PDOException $e) {
			$ret["code"] = 201;
			$ret['message'] = 'Fail' . $e;
			return json($ret);
		}
	}

	//-------------------------------------------------------------------支付--------------------------------------------------------
	public function payOrder()
	{
		$params = $this->request->param();
		$openid = isset($params["openid"]) ? $params["openid"] : "";
		$res = $this->checkOpenid($openid);

		if ($res["code"] != 200) {
			$ret['code'] = 201;
			$ret['message'] = '无权限操作';
			return json($ret);
		}
		//获得会员 编号
		$mNo = $res["data"][0]["m_no"];

		// 检验订单是否存在
		$orderNum = isset($params["orderNum"]) ? $params["orderNum"] : "";
		$sql = "select total_price ,type from hd_order where number='{$orderNum}'";
		$result = Db::query($sql);
		if (count($result) == 0) {
			$ret['code'] = 201;
			$ret['message'] = '无此订单';
			return json($ret);
		}
		// 订单存在，得到订单金额
		$totalPrice = (float) $result[0]["total_price"];
		$type = $result[0]["type"]; // shop or detect
		$payType = isset($params["payType"]) ? $params["payType"] : "" + 0;  // 1 or 2

		if ($payType == 1) { // 微信支付
			$wxOrderData = new \WxPayUnifiedOrder();
			$wxOrderData->SetOut_trade_no($orderNum);
			$wxOrderData->SetTotal_fee($totalPrice * 100); // 分 -> 元
			$wxOrderData->SetTrade_type("JSAPI");
			$wxOrderData->SetBody("医道商城健康监测");  // 商品描述	
			$wxOrderData->SetOpenid($openid);
			$wxOrderData->SetTime_start(date("YmdHis"));
			$wxOrderData->SetTime_expire(date("YmdHis", time() + 600));
			// $wxOrderData->SetAttach("test");   // 附加数据	
			// $wxOrderData->SetGoods_tag("test");  // 订单优惠标记

			$wxConfig = new \WxPayConfig();
			$wxOrder = \WxPayApi::unifiedOrder($wxConfig, $wxOrderData);

			$wxJspay = new \WxPayJsApiPay();
			$wxJspay->SetAppid($wxConfig->GetAppId());
			$wxJspay->SetNonceStr(\WxPayApi::getNonceStr());
			$wxJspay->SetTimeStamp(time());
			$wxJspay->SetPackage("prepay_id=" . $wxOrder["prepay_id"]);
			$wxJspay->SetPaySign($wxJspay->MakeSign($wxConfig));

			$parameters = json_encode($wxJspay->GetValues());
			$ret["code"] = 200;
			$ret["order"] = $wxOrder;
			$ret["parameters"] = $parameters;
			$ret["url"] = $wxConfig->GetNotifyUrl();

			return json($ret);
		} elseif ($payType == 2) { // 余额支付
			Db::startTrans();
			try {
				// 检验用户余额是否足够
				$sql = "select balance from hd_member where openid='$openid'";
				$result = Db::query($sql);
				$balance = (float) $result[0]["balance"];
				if ($balance < $totalPrice) {
					$ret['code'] = 201;
					$ret['message'] = '账户余额不足';

					Db::rollback();
					return json($ret);
				}
				// --更新用户余额
				$balance = $balance - $totalPrice;
				$sql = "update hd_member set balance=$balance where openid='$openid'";
				Db::execute($sql);

				// --插入账单表
				$sql = "INSERT INTO `hd_member_bill`( `member_no`, `business_no`, `mb_type`, `mb_balance`, `createtime`, `current_fee`, `user_type`,`bill_item`,`comments`) 
											 VALUES ('$mNo', 		'$orderNum', 	'现金', 	$balance, 	now(), 			-$totalPrice, '会员',	'用户付款',		'')";
				Db::execute($sql);

				// -- 更新订单状态
				if ($type == "shop")
					$status = "待发货";
				else
					$status = "待检测";
				$sql = "update hd_order set pay_type='余额支付',pay_status='已支付',openid='$openid', status='$status',paytime=now() where number='$orderNum'";
				Db::execute($sql);

				Db::commit();
				$ret["code"] = 200;
				$ret["message"] = "Success";
				return json($ret);
			} catch (PDOException $e) {
				Db::rollback();
				$ret['code'] = 201;
				$ret['message'] = 'Fail' . $e;
				return json($ret);
			}
		} elseif ($payType == 3) { // 现金支付
			Db::startTrans();
			try {
				// -- 更新订单状态
				if ($type == "shop")
					$status = "待发货";
				else
					$status = "待检测";
				$sql = "update hd_order set pay_type='现金支付',pay_status='已支付', status='$status',openid='$openid',paytime=now() where number='$orderNum'";
				Db::execute($sql);

				// --插入账单表
				$sql = "INSERT INTO `hd_member_bill`( `member_no`, `business_no`, `mb_type`,  `createtime`, `current_fee`, `user_type`,`bill_item`,`comments`) 
											 VALUES ('$mNo', 		'$orderNum', '现金', 		now(), 		-$totalPrice, 	'会员',		'用户付款',		'')";
				Db::execute($sql);

				Db::commit();
				$ret["code"] = 200;
				$ret["message"] = "Success";
				return json($ret);
			} catch (PDOException $e) {
				Db::rollback();
				$ret['code'] = 201;
				$ret['message'] = 'Fail' . $e;
				return json($ret);
			}
		} elseif ($payType == 4) { // 医保支付
			Db::startTrans();
			try {
				// -- 更新订单状态
				if ($type == "shop")
					$status = "待发货";
				else
					$status = "待检测";
				$sql = "update hd_order set pay_type='医保支付',pay_status='已支付', status='$status',openid='$openid',paytime=now() where number='$orderNum'";
				Db::execute($sql);

				// --插入账单表
				$sql = "INSERT INTO `hd_member_bill`( `member_no`, `business_no`, `mb_type`,  `createtime`, `current_fee`, `user_type`,`bill_item`,`comments`) 
											 VALUES ('$mNo', 		'$orderNum', '现金', 		now(), 		-$totalPrice, 	'会员',		'用户付款',		'')";
				Db::execute($sql);

				Db::commit();
				$ret["code"] = 200;
				$ret["message"] = "Success";
				return json($ret);
			} catch (PDOException $e) {
				Db::rollback();
				$ret['code'] = 201;
				$ret['message'] = 'Fail' . $e;
				return json($ret);
			}
		} else {
			$ret['code'] = 201;
			$ret['message'] = '无此支付方式';
			return json($ret);
		}
	}

	// 取消订单
	public function cancelOrder()
	{
		$params = $this->request->param();
		$openid = isset($params["openid"]) ? $params["openid"] : "";
		$memberRes = $this->checkOpenid($openid);

		if ($memberRes["code"] != 200) {
			$ret['code'] = 201;
			$ret['message'] = '无权限操作';
			return json($ret);
		}

		try {
			$orderNum = isset($params["orderNum"]) ? $params["orderNum"] : "";

			$sql = "update hd_order set status='已取消' where number='$orderNum'";
			Db::execute($sql);

			$ret['code'] = 200;
			$ret['message'] = "success";
			return json($ret);
		} catch (Exception $e) {
			$ret['code'] = 201;
			$ret['message'] = "fail" . $e;
			return json($ret);
		}
	}

	//------------------------------------------------------------------小程序码-------------------------------------------------------
	public function getQrCode()
	{
		$params = $this->request->param();

		try { // client_credential
			// 。获取后台访问微信服务器的token
			$get_acces_token_url =  'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential'  . '&appid=' . self::$APPID . '&secret=' . self::$SECRET;
			$curl = curl_init();
			curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
			curl_setopt($curl, CURLOPT_TIMEOUT, 500);
			curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
			curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
			curl_setopt($curl, CURLOPT_URL, $get_acces_token_url);

			$res = curl_exec($curl);
			curl_close($curl);

			$json_obj = json_decode($res, true);
			$accessToken = $json_obj["access_token"]; // 凭证
			$expireIn = $json_obj["expires_in"]; // 凭证有效时间


			// 。获得分享二维码图片
			$get_wxcode_url = 'https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=' . $accessToken;
			$curl = curl_init();

			curl_setopt($curl, CURLOPT_URL, $get_wxcode_url);
			curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
			curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
			curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
			curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
			curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
			curl_setopt($curl, CURLOPT_POST, 1);
			curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($params));
			curl_setopt($curl, CURLOPT_TIMEOUT, 30);
			curl_setopt($curl, CURLOPT_HEADER, 0);
			curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

			$res = curl_exec($curl);
			curl_close($curl);

			// 。返回给小程序
			$base64_image = "data:image/jpeg;base64," . base64_encode($res);

			return json($base64_image);
		} catch (PDOException $e) {
			$ret['code'] = 201;
			$ret['message'] = 'Fail' . $e;
			return json($ret);
		}
	}
}
